package com.example.timeplanning_teacher;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import es.dmoral.toasty.Toasty;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.timeplanning_teacher.tools.ClassInfo;
import com.example.timeplanning_teacher.tools.Config;
import com.example.timeplanning_teacher.tools.CurriculumResponse;
import com.example.timeplanning_teacher.tools.SingleTask;
import com.example.timeplanning_teacher.tools.myCallback;
import com.google.gson.Gson;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;

import org.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.regex.Pattern;

public class PlanActivity extends AppCompatActivity {

    private static final String TAG = "PlanActivity";
    public Context mContext;
    private static ArrayList<ClassInfo> allClasses = null;
    private GridLayout allClassGrid;
    private GridLayout allClassGrid_home;
    private TextView weekIndexTextView;

    private SharedPreferences sp;
    private String student_username;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_plan);
        QMUIStatusBarHelper.translucent(this);
        QMUIStatusBarHelper.setStatusBarLightMode(this);
        mContext = this;
        allClassGrid = findViewById(R.id.main_grid_layout_all_class);
        allClassGrid_home = allClassGrid;
        weekIndexTextView = findViewById(R.id.main_text_view_week_index);

        sp = getSharedPreferences("parent", Context.MODE_PRIVATE);
        student_username = sp.getString("student_username","");

        //取值
        Intent intent = getIntent();
        String title=intent.getStringExtra("title");        //获取Intent中的数据
        weekIndexTextView.setText(title);//把外面传进来的标题写到第一行去

        String monday = weekIndexTextView.getText().subSequence(0,4)+"-"+weekIndexTextView.getText().subSequence(5,7)+"-"+weekIndexTextView.getText().subSequence(8,10);
        String sunday = weekIndexTextView.getText().subSequence(13,18)+"-"+weekIndexTextView.getText().subSequence(19,21)+"-"+weekIndexTextView.getText().subSequence(22,24);
        getTask(monday,sunday);
    }

    private void getTask(String start_day,String end_day)
    {
        HashMap<String, String> parm = new HashMap<>();
        parm.put("username", student_username);
        parm.put("start_day", start_day);
        parm.put("end_day", end_day);
        doPost(Config.taskGet_url, parm, new myCallback() {
            @Override
            public void onSuccess(String res) {
                PlanActivity.this.runOnUiThread(new Runnable() {
                    @RequiresApi(api = Build.VERSION_CODES.M)
                    public void run() {
                        CurriculumResponse Response = new Gson().fromJson(res, CurriculumResponse.class);
                        switch (Response.getMsg()) {
                            case "success":
                                showToastySyncSuccess("找到此人的任务");
                                showTask(Response);//把取到的的任务展示出来
                                break;
                            case "fail":
                                showToastySyncError("没有找到此人的任务");
                                break;
                        }
                    }
                });

            }

            @Override
            public void onFailure(Exception e) {
                PlanActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        //recovery();
                        showToastySyncError("连接失败！");
                    }
                });
            }
        });
    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void showTask(CurriculumResponse Response) {
        getStoredData(Response);
        addAllClass();
    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void getStoredData(CurriculumResponse Response) {
        allClasses = new ArrayList<>();
        int[] position = new int[3];
//        for (SingleTask ex : Response.getData()) {
//            showToastySyncError(ex.getSubject()+" "+ex.getType()+" "+ex.getStart_time()+ex.getEnd_time());
//        }
        for (SingleTask ex : Response.getData()) {
            //showToastySyncError(ex.getStart_time()+ex.getEnd_time());

            position = PutTaskByTime(ex.getStart_time(), ex.getEnd_time(), ex.getStart_day());
            //showToastySyncError(position[1]+" "+position[2]);
            allClasses.add(new ClassInfo(ex.getSubject(), ex.getType(), position[0], position[1], position[2]));
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void addAllClass() {
        //生成满屏的淡灰色块
        for (int i = 1; i <= 7; i++) { //一周7天
            for (int j = 1; j <= 34; ) { //一天34个时间段
                View child = new TextView(this);
                GridLayout.Spec rowSpec = GridLayout.spec(j - 1, 1);
                GridLayout.Spec columnSpec = GridLayout.spec(i, 1, 1.0f);
                GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams(rowSpec, columnSpec);
                layoutParams.width = 0;
                layoutParams.height = GridLayout.LayoutParams.WRAP_CONTENT;
                layoutParams.setGravity(Gravity.FILL);
                child.setBackgroundColor(getResources().getColor(R.color.lightGray, null));
                allClassGrid.addView(child, layoutParams);
                j += 1;
            }
        }

        for (int k = 0; k < allClasses.size(); k++) {
            ClassInfo tmpClassInfo = allClasses.get(k);
            TextView textView = new TextView(new ContextThemeWrapper(this, R.style.TextViewClassInfo));
            textView.setText(tmpClassInfo.toClassInfoString());
            textView.setLayoutParams(new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER));
            CardView cardView = new CardView(new ContextThemeWrapper(this, R.style.CardViewClass));
            cardView.addView(textView);
            cardView.setCardBackgroundColor(tmpClassInfo.getBgColor());
            GridLayout.Spec rowSpec = GridLayout.spec(allClasses.get(k).getClassStartIndex() - 1, tmpClassInfo.getClassPeriod());
            GridLayout.Spec columnSpec = GridLayout.spec(allClasses.get(k).getWeekdayIndex(), 1.0f);
            GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams(rowSpec, columnSpec);
            layoutParams.setGravity(Gravity.FILL);
            layoutParams.height = 0;
            layoutParams.width = 0;
            allClassGrid.addView(cardView, layoutParams);
        }
    }

    private int[] PutTaskByTime(int start_time, int end_time, String start_day) {
        String regEx = "[^0-9]+";//正则表达式
        Pattern pattern = Pattern.compile(regEx);
        //用定义好的正则表达式拆分字符串，，把字符串中的数字留出来
        String[] cs = pattern.split(start_day);
//        String[] ce = pattern.split(ent_time);
//        int startTime_to_Minute = (Integer.valueOf(cs[3]) - 6) * 60 + Integer.valueOf(cs[4]);
//        int entTime_to_Minute = (Integer.valueOf(ce[3]) - 6) * 60 + Integer.valueOf(ce[4]);
//        int start = startTime_to_Minute / 30 + 1;//起始点位
//        int len = (entTime_to_Minute - startTime_to_Minute) / 30;

//        System.out.println(Arrays.toString(cs));
//        System.out.println(Arrays.toString(ce));

        try {
            String date = Integer.valueOf(cs[0]) + "年" + Integer.valueOf(cs[1]) + "月" + Integer.valueOf(cs[2]) + "日";
            SimpleDateFormat geshi = new SimpleDateFormat("y年M月d日", Locale.CHINA);
            Date date_new = geshi.parse(date);
            Calendar rili = Calendar.getInstance();
            rili.setTime(date_new);
            rili.setFirstDayOfWeek(Calendar.MONDAY);
            int today_of_week = rili.get(Calendar.DAY_OF_WEEK);

            int today_of_week_new;
            if (today_of_week == 1) today_of_week_new = 7;
            else today_of_week_new = today_of_week - 1;
            int[] position = new int[3];
            position[0] = today_of_week_new;
            position[1] = start_time+1;
            position[2] = end_time-start_time;
            return position;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
    public void lastWeek(View view) {
        try {
            String monday = weekIndexTextView.getText().subSequence(0,4)+"-"+weekIndexTextView.getText().subSequence(5,7)+"-"+weekIndexTextView.getText().subSequence(8,10);
            String sunday = weekIndexTextView.getText().subSequence(13,18)+"-"+weekIndexTextView.getText().subSequence(19,21)+"-"+weekIndexTextView.getText().subSequence(22,24);

            Date dateMonday = new SimpleDateFormat("yyyy-MM-dd").parse(monday);
            //String now = new SimpleDateFormat("yyyy年MM月dd日").format(dateMonday);
            //System.out.println(now);
            Date dateSunday = new SimpleDateFormat("yyyy-MM-dd").parse(sunday);
            //String now2 = new SimpleDateFormat("yyyy年MM月dd日").format(dateSunday);
            //System.out.println(now2);

            Calendar cal = Calendar.getInstance();
            cal.setTime(dateMonday);
            cal.add(Calendar.DAY_OF_MONTH, -7);//增加7天
            Date dateNextMonday=cal.getTime();//Calendar转为Date类型
            cal.setTime(dateSunday);
            cal.add(Calendar.DAY_OF_MONTH, -7);//增加7天
            Date dateNextSunday=cal.getTime();//Calendar转为Date类型

            String now1 = new SimpleDateFormat("yyyy年MM月dd日").format(dateNextMonday);
            String now2 = new SimpleDateFormat("yyyy年MM月dd日").format(dateNextSunday);

            Intent intent = new Intent(this, PlanActivity.class);
            intent.putExtra("title",now1+" ~ "+now2);//当前日期所在的周，用于打印在第一行的串,也就是标题，整体传过去
            startActivity(intent);
            finish();

        } catch (Exception e) { e.printStackTrace(); }
    }
    public void nextWeek(View view) {
        try {
            String monday = weekIndexTextView.getText().subSequence(0,4)+"-"+weekIndexTextView.getText().subSequence(5,7)+"-"+weekIndexTextView.getText().subSequence(8,10);
            String sunday = weekIndexTextView.getText().subSequence(13,18)+"-"+weekIndexTextView.getText().subSequence(19,21)+"-"+weekIndexTextView.getText().subSequence(22,24);

            Date dateMonday = new SimpleDateFormat("yyyy-MM-dd").parse(monday);
            //String now = new SimpleDateFormat("yyyy年MM月dd日").format(dateMonday);
            //System.out.println(now);
            Date dateSunday = new SimpleDateFormat("yyyy-MM-dd").parse(sunday);
            //String now2 = new SimpleDateFormat("yyyy年MM月dd日").format(dateSunday);
            //System.out.println(now2);

            Calendar cal = Calendar.getInstance();
            cal.setTime(dateMonday);
            cal.add(Calendar.DAY_OF_MONTH, 7);//增加7天
            Date dateNextMonday=cal.getTime();//Calendar转为Date类型
            cal.setTime(dateSunday);
            cal.add(Calendar.DAY_OF_MONTH, 7);//增加7天
            Date dateNextSunday=cal.getTime();//Calendar转为Date类型

            String now1 = new SimpleDateFormat("yyyy年MM月dd日").format(dateNextMonday);
            String now2 = new SimpleDateFormat("yyyy年MM月dd日").format(dateNextSunday);



            Intent intent = new Intent(this, PlanActivity.class);
            intent.putExtra("title",now1+" ~ "+now2);//当前日期所在的周，用于打印在第一行的串,也就是标题，整体传过去
            startActivity(intent);
            finish();

        } catch (Exception e) { e.printStackTrace(); }
    }

    protected void doPost(String url , HashMap<String,String> parm , myCallback callback){
        String jsonStr = new JSONObject(parm).toString();
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody =
                RequestBody.create(MediaType.parse("application/json;charset=utf-8")
                        ,jsonStr);
        final Request request = new Request.Builder()
                .url(url)
                .addHeader("contentType","application/json;charset=utf-8")
                .post(requestBody)//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                callback.onSuccess(str);
            }
        });
    }

    public void showToastySyncError(String msg){
//        Looper.prepare();
//        Toast.makeText(mContext,msg,Toast.LENGTH_SHORT).show();
//        Looper.loop();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toasty.error(mContext, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }
    public void showToastySyncSuccess(String msg){
//        Looper.prepare();
//        Toast.makeText(mContext,msg,Toast.LENGTH_SHORT).show();
//        Looper.loop();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toasty.success(mContext, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private String setSemesterWeek() {
        SimpleDateFormat geshi = new SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA);
        java.util.Calendar rili = java.util.Calendar.getInstance(Locale.CHINA);

        rili.setFirstDayOfWeek(java.util.Calendar.MONDAY);

        //当前时间，貌似多余，其实是为了所有可能的系统一致
        rili.setTimeInMillis(System.currentTimeMillis());

        rili.set(java.util.Calendar.DAY_OF_WEEK, java.util.Calendar.MONDAY);
        String monday = geshi.format(rili.getTime()).toString();
        rili.set(java.util.Calendar.DAY_OF_WEEK, java.util.Calendar.SUNDAY);
        String sunday = geshi.format(rili.getTime()).toString();
        return monday+" ~ "+sunday;
    }
}